<script setup lang="ts">
import { computed, ref } from 'vue';
import { useAuthStore } from '@/store';
import { storeToRefs } from 'pinia';
import { useRouterPush } from '@/composables';
import { useNurseOrders } from '@/service';
import { showToast, showLoading, hideLoading, getCurrentInstance, requestPayment, getStorageSync, setStorageSync, removeStorageSync } from '@tarojs/taro';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { useDayjs, useEmitter } from '@/hooks/common';
import PayFooter from './components/PayFooter.vue';
import UserInfo from './components/UserInfo.vue';
import GoodsInfo from './components/GoodsInfo.vue';
import ServiceOptions from './components/ServiceOptions.vue';

const emitter = useEmitter();

const { $dayjs } = useDayjs();

const { addByWeChat, payByWeChat, queryByWeChat, closeByWeChat } = useNurseOrders();

const { toOrders } = useRouterPush();

const { nurseUser } = storeToRefs(useAuthStore());

const {
    router: {
        params: { orderId, goodsId, pname, pid, name, num, pic, unit, nurseType, nurseTypeText, price, pay, fromCart }
    }
}: any = getCurrentInstance();

definePageConfig({
    navigationBarTitleText: fromCart === 'true' ? '订单确认' : '付款支付'
});

// 处理购物车数据
const getInitialOrderDetails = () => {
    if (fromCart === 'true') {
        const cartData = getStorageSync('cart_checkout_data');
        if (cartData && cartData.items) {
            return cartData.items.map((item: any) => ({
                price: item.price,
                unit: item.unit || '',
                num: item.quantity,
                goodsName: item.typeName,
                goodsId: item.id,
                pname: item.pname || '',
                pid: item.pid || ''
            }));
        }
    }
    return [
        {
            price,
            unit,
            num,
            goodsName: name,
            goodsId,
            pname,
            pid
        }
    ];
};

const formData = ref<any>({
    out_trade_no: undefined,
    name: '',
    address: '',
    hospital: nurseUser.value.defaultHospital,
    hospitalId: nurseUser.value.defaultHospital,
    nurseUserOrdersDetails: getInitialOrderDetails(),
    specialDetails: [],
    specialAmt: '',
    beginDate: $dayjs().add(+2, 'day').format('YYYY-MM-DD'),
    endDate: $dayjs().add(+2, 'day').format('YYYY-MM-DD'),
    remark: '',
    addrId: '',
    familyId: '',
    userId: nurseUser.value.id,
    preAmt: undefined,
    orderText: '',
    nurseType,
    orderId,
    end: 0,
    isGoHome: '0',
    ispickup: '0',
    urgentId: '',
    urgentName: '',
    urgentFee: 0,
    expertId: '',
    expertName: '',
    expertFee: 0,
    distanceId: '',
    distanceName: '远程费',
    distanceFee: 0,
    distanceOldFee: 0,
    expertOldFee: 0,
    expertNum: 1,
    distanceNum: 1,
    nightId: -1,
    totalPrice: undefined,
    medicationOrderDetails: [],
    distanceList: []
});

const isOrder = computed(() => formData.value?.orderId && formData.value.orderId !== 'undefined');



const loading = ref(false);
const status = ref('');

const ruleUser = ref<any>(null);

const ruleService = ref<any>(null);

// 格式化服务类型显示
const formatNurseType = (type: string) => {
    const typeMap: Record<string, string> = {
        '1': '护理',
        '2': '护工',
        '3': '导医',
        '4': '陪诊'
    };
    return typeMap[type] || type;
};

const submit = async () => {
    // 同时验证两个表单
    const [userInfoValid, serviceOptionsValid] = await Promise.all([
        ruleUser.value?.validate(),
        ruleService.value?.validate()
    ]);

    if (!userInfoValid?.valid || !serviceOptionsValid?.valid) {
        return;
    }

    loading.value = true;

    let payInfo: any;

    if (!formData.value.orderId) {
        showLoading({ title: '正在下单...' });

        // 生成订单文本
        const generateOrderText = () => {
            if (fromCart === 'true') {
                // 从购物车过来，处理多商品
                const items = formData.value.nurseUserOrdersDetails;
                return items.map((item: any) => `[${item.goodsName}]`).join(', ');
            } else {
                // 单商品
                return `[${nurseTypeText}]${pname !== name ? `[${pname}]` : ''}-[${name}]`;
            }
        };

        const { error, success } = await addByWeChat({
            ...formData.value,
            beginDate: `${formData.value.beginDate} 00:00:00`,
            endDate: `${formData.value.endDate} 23:59:59`,
            orderText: generateOrderText()
        });

        if (!error && success) {
            showToast({
                title: '下单成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });
            payInfo = success;
        }
    } else {
        showLoading({ title: '正在调取支付...' });

        const { error, success } = await payByWeChat(formData.value.orderId);

        if (!error && success) {
            showToast({
                title: '调取支付成功',
                icon: 'success',
                duration: SUCCESS_MSG_DURATION
            });
            payInfo = success;
        } else {
            gotoOrder();
        }
    }
    const { timestamp, noncestr, package: packAge, sign } = payInfo;

    await requestPayment({
        timeStamp: timestamp,
        nonceStr: noncestr,
        package: packAge,
        paySign: sign,
        signType: 'RSA',
        fail: () => {
            if (pay !== '1') gotoOrder();
        },
        complete() {
            hideLoading();
            loading.value = false;
        },
        success: res => {
            if (res.errMsg == 'requestPayment:ok') {
                showToast({
                    title: '支付成功！',
                    icon: 'success',
                    duration: 1500
                });
                
                // 如果是从购物车过来，清除已购买的商品
                if (fromCart === 'true') {
                    const cartData = getStorageSync('cart_checkout_data');
                    if (cartData && cartData.items) {
                        // 这里需要导入购物车store来清除商品
                        // 由于在setup函数外部，需要通过其他方式处理
                        // 可以通过事件或在gotoOrder中处理
                        const itemIds = cartData.items.map((item: any) => item.id);
                        setStorageSync('clear_cart_items', itemIds);
                    }
                    // 清除购物车结算数据
                    removeStorageSync('cart_checkout_data');
                }
                
                setTimeout(() => {
                    gotoOrder();
                }, 1500);
            }
        }
    });
};

const amt = computed(() => {
    // 如果有原始订单数据中的总价，优先使用
    if (formData.value.totalPrice !== undefined) {
        return formData.value.totalPrice;
    }
    
    // 否则计算总价
    const detailsFee = formData.value.nurseUserOrdersDetails.reduce(
        (prev: number, cur: { num: number; price: number }) => cur.num * cur.price + prev,
        0
    );
    return detailsFee + formData.value.urgentFee + formData.value.expertFee + formData.value.distanceFee;
});

async function getData() {
    if (!isOrder.value) return;

    const { error, success } = await queryByWeChat( formData.value.orderId );

    if (!error && success) {
        // 设置订单状态
        status.value = success.status;
        
        const expiryTime = $dayjs(success.expiryTime);

        let diff = 0;
        // 待付款状态才提示
        if (success.status == '1') {
            diff = expiryTime.diff($dayjs(), 'second', true);
        }

        const distanceFee = success.nurseUserOrdersDetails.reduce(
            (prev: number, cur: { num: number; price: number; pid: string; costTypeName: string }) => {
                if (cur.pid == '1') {
                    formData.value.distanceName = cur.costTypeName;
                    return prev + cur.num * cur.price;
                }
                return prev;
            },
            0
        );
        const expertFee = success.nurseUserOrdersDetails.reduce(
            (prev: number, cur: { num: number; price: number; pid: string; costTypeName: string }) => {
                if (cur.pid == '2') {
                    formData.value.expertName = cur.costTypeName;
                    return prev + cur.num * cur.price;
                }
                return prev;
            },
            0
        );
        const urgentFee = success.nurseUserOrdersDetails.reduce(
            (prev: number, cur: { num: number; price: number; pid: string; costTypeName: string }) => {
                if (cur.pid == '3') {
                    formData.value.urgentName = cur.costTypeName;
                    return prev + cur.num * cur.price;
                }
                return prev;
            },
            0
        );

        const nurseUserOrdersDetails = success.nurseUserOrdersDetails.filter(
            (item: any) => !['1', '2', '3'].includes(item.pid)
        );

        // 解析 orderJson 获取原始订单数据
        let originalOrderData = null;
        if (success.orderJson) {
            try {
                originalOrderData = JSON.parse(success.orderJson);
            } catch (error) {
                // 解析 orderJson 失败
            }
        }

        // 如果有原始订单数据，优先使用原始数据
        if (originalOrderData) {
            formData.value = {
                ...formData.value,
                orderId: formData.value.orderId, // 保持 orderId
                out_trade_no: formData.value.orderId,
                // 使用原始订单数据
                nurseUserOrdersDetails: originalOrderData.nurseUserOrdersDetails || [...nurseUserOrdersDetails],
                beginDate: originalOrderData.beginDate || success.beginDate || '无',
                endDate: originalOrderData.endDate || success.endDate || '无',
                remark: originalOrderData.remark || success.remark || '无',
                preAmt: success?.preAmt || '0',
                // 使用原始订单数据中的费用信息
                urgentFee: originalOrderData.urgentFee || urgentFee,
                urgentId: originalOrderData.urgentId || '',
                urgentName: originalOrderData.urgentName || formData.value.urgentName,
                expertFee: originalOrderData.expertFee || expertFee,
                expertId: originalOrderData.expertId || '',
                expertName: originalOrderData.expertName || formData.value.expertName,
                distanceFee: originalOrderData.distanceFee || distanceFee,
                distanceId: originalOrderData.distanceId || '',
                distanceName: originalOrderData.distanceName || formData.value.distanceName,
                // 使用原始订单数据中的用户信息
                name: originalOrderData.name || `${success.familyName}${success.phone}`,
                address: originalOrderData.address || `${success.areaName}${success.address}`,
                hospital: originalOrderData.hospital || `${success.hospitalName}${success.deptName}${success.bedName}`,
                hospitalId: originalOrderData.hospitalId || success.hospitalId,
                addrId: originalOrderData.addrId || success.addrId,
                familyId: originalOrderData.familyId || success.familyId,
                isGoHome: originalOrderData.isGoHome || success?.isGoHome || '0',
                // 其他原始数据
                nurseType: originalOrderData.nurseType || formData.value.nurseType,
                orderText: originalOrderData.orderText || success.orderText,
                totalPrice: originalOrderData.totalPrice,
                // 如果有药品订单详情，也包含进来
                medicationOrderDetails: originalOrderData.medicationOrderDetails || [],
                // 根据数据格式添加其他字段
                nightId: originalOrderData.nightId || -1,
                ispickup: originalOrderData.ispickup || '0',
                distanceOldFee: originalOrderData.distanceOldFee || 0,
                expertOldFee: originalOrderData.expertOldFee || 0,
                expertNum: originalOrderData.expertNum || 1,
                distanceNum: originalOrderData.distanceNum || 1,
                specialDetails: originalOrderData.specialDetails || [],
                specialAmt: originalOrderData.specialAmt || ''
            };
        } else {
            // 如果没有原始订单数据，使用现有逻辑
            formData.value = {
                ...formData.value,
                orderId: formData.value.orderId, // 保持 orderId
                out_trade_no: formData.value.orderId,
                nurseUserOrdersDetails: [...nurseUserOrdersDetails],
                beginDate: success.beginDate || '无',
                endDate: success.endDate || '无',
                remark: success.remark || '无',
                preAmt: success?.preAmt || '0',
                urgentFee,
                expertFee,
                distanceFee,
                name: `${success.familyName}${success.phone}`,
                address: `${success.areaName}${success.address}`,
                hospital: `${success.hospitalName}${success.deptName}${success.bedName}`,
                isGoHome: success?.isGoHome || '0'
            };
        }
        if (diff <= 0) {
            formData.value.end = 0;
        } else {
            formData.value.end = expiryTime.valueOf();
            if (pay == '1') submit();
        }
    }
}
getData();

const gotoOrder = () => {
    emitter.$emit('order_refresh');
    toOrders();
};
const end = () => {
    setTimeout(() => {
        gotoOrder();
    }, 2000);
};
async function close() {
    loading.value = true;
    showLoading({ title: '正在取消...' });
    const { error, success } = await closeByWeChat(formData.value.orderId);
    if (!error && success) {
        // hideLoading()
        showToast({
            title: '取消成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
        gotoOrder();
    }

    hideLoading();
    loading.value = false;
}
</script>

<template>
    <basic-layout>
        <!-- <custom-navbar title="付款支付" showLeft /> -->
        <view class="w-375px text-primary flex-col-center">
            <view class="w-360px mb-100px">
                <view v-if="formData.end" class="mt-2 w-full flex-center text-base">
                    <view class="mr-1">请在</view>
                    <nut-countdown class="w-fit text-center" :end-time="formData.end" millisecond format="mm:ss:SS"
                        @end="end" />
                    <view class="ml-1">内支付</view>
                </view>
                
                <!-- 调试信息：显示是否使用了原始订单数据 -->
                <!-- <view v-if="formData.totalPrice !== undefined" class="bg-blue-50 p-3 mb-3 rounded text-xs text-blue-600">
                    <text>📋 使用原始订单数据</text>
                    <view class="mt-1">总价: ¥{{ formData.totalPrice }}</view>
                    <view class="mt-1">服务时间: {{ formData.beginDate }} - {{ formData.endDate }}</view>
                    <view class="mt-1">服务类型: {{ formatNurseType(formData.nurseType) }}</view>
                    <view v-if="formData.urgentFee > 0" class="mt-1">加急费: ¥{{ formData.urgentFee }} ({{ formData.urgentName }})</view>
                    <view v-if="formData.distanceFee > 0" class="mt-1">远程费: ¥{{ formData.distanceFee }} ({{ formData.distanceName }})</view>
                    <view v-if="formData.expertFee > 0" class="mt-1">专家费: ¥{{ formData.expertFee }} ({{ formData.expertName }})</view>
                    <view v-if="formData.medicationOrderDetails && formData.medicationOrderDetails.length > 0" class="mt-1">
                        药品订单: {{ formData.medicationOrderDetails.length }}项
                    </view>
                    <view v-if="formData.remark" class="mt-1">备注: {{ formData.remark }}</view>
                </view> -->
                
                <!-- 订单详情展示 -->
                <view v-if="formData.totalPrice !== undefined" class="bg-white p-4 mb-3 rounded shadow-sm">
                    <view class="text-sm font-medium mb-3 text-gray-800">订单详情</view>
                    
                    <!-- 商品信息 -->
                    <view v-for="(item, index) in formData.nurseUserOrdersDetails" :key="index" class="mb-3 p-3 bg-gray-50 rounded">
                        <view class="flex justify-between items-center">
                            <view class="flex-1">
                                <view class="text-sm font-medium text-gray-800">{{ item.goodsName }}</view>
                                <view class="text-xs text-gray-500 mt-1">{{ item.pname }}</view>
                                <view class="text-xs text-gray-500">数量: {{ item.num }} {{ item.unit }}</view>
                            </view>
                            <view class="text-sm font-bold text-red-500">¥{{ (item.price * item.num).toFixed(2) }}</view>
                        </view>
                    </view>
                    
                    <!-- 费用明细 -->
                    <view class="border-t pt-3 mt-3">
                        <view class="flex justify-between items-center mb-2">
                            <text class="text-sm text-gray-600">商品小计</text>
                            <text class="text-sm text-gray-600">¥{{ formData.nurseUserOrdersDetails.reduce((sum: number, item: any) => sum + (item.price * item.num), 0).toFixed(2) }}</text>
                        </view>
                        <view v-if="formData.urgentFee > 0" class="flex justify-between items-center mb-2">
                            <text class="text-sm text-gray-600">{{ formData.urgentName }}</text>
                            <text class="text-sm text-gray-600">¥{{ formData.urgentFee.toFixed(2) }}</text>
                        </view>
                        <view v-if="formData.distanceFee > 0" class="flex justify-between items-center mb-2">
                            <text class="text-sm text-gray-600">{{ formData.distanceName }}</text>
                            <text class="text-sm text-gray-600">¥{{ formData.distanceFee.toFixed(2) }}</text>
                        </view>
                        <view v-if="formData.expertFee > 0" class="flex justify-between items-center mb-2">
                            <text class="text-sm text-gray-600">{{ formData.expertName }}</text>
                            <text class="text-sm text-gray-600">¥{{ formData.expertFee.toFixed(2) }}</text>
                        </view>
                        <view class="flex justify-between items-center pt-2 border-t">
                            <text class="text-base font-bold text-gray-800">总计</text>
                            <text class="text-base font-bold text-red-500">¥{{ formData.totalPrice.toFixed(2) }}</text>
                        </view>
                    </view>
                </view>
                
                <UserInfo ref="ruleUser" :nurse-user="nurseUser" :form-data="formData" :is-order="isOrder" />
                <GoodsInfo :nurse-user-orders-details="formData.nurseUserOrdersDetails" :is-order="isOrder" :pic="pic"
                    :num="num" />
                <ServiceOptions ref="ruleService" :form-data="formData" :is-order="isOrder" />
            </view>
            <PayFooter :form-data="formData" :loading="loading" :amt="amt" :status="status" :is-order="isOrder" @submit="submit"
                @close="close" />
        </view>
    </basic-layout>
</template>
